<template>
    <section>
        <!--搜索工具条-->
        <el-col :span="24" class="toolbar" style="text-align:right;">
            <el-link v-if="role == 1" type="primary" href="./docs/template/高等学校实验室安全自查自纠报告.doc" target="_blank">下载模板</el-link>
            <el-link v-else type="primary" href="./docs/template/省级教育行政部门安全自查工作总结.doc" target="_blank">下载模板</el-link>
            <el-button style="margin-left:20px;" type="primary" @click="submitReport" icon="el-icon-plus">提交自查报告</el-button>
        </el-col>
        <!--搜索结果表格-->
        <el-table
                :header-row-style="headerRowStyle"
                :data="tableData"
                stripe
                v-loading="listLoading"
                style="width: 100%;">
            <el-table-column
                    label="序号"
                    type="index"
                    width="60"
                    align="center">
            </el-table-column>
            <el-table-column
                    align="center"
                    label="年份"
                    prop="year">
            </el-table-column>
            <el-table-column
                    align="center"
                    label="发现总隐患数"
                    prop="total_bugs">
            </el-table-column>
            <el-table-column
                    align="center"
                    label="已整改数"
                    prop="total_fix_bugs">
            </el-table-column>
            <el-table-column
                    align="center"
                    label="整改完成率"
                    :formatter="fixFormatter"
                    prop="total_fix_bugs">
            </el-table-column>
            <el-table-column
                    align="center"
                    label="提交日期"
                    prop="gmt_modified">
            </el-table-column>
            <el-table-column
                    align="center" label="操作" prop="id" >
                <template slot-scope="scope">
                    <el-button
                            @click="dowReportWord(scope.row)"
                            type="primary"  >
                        下载报告
                    </el-button>
                    <el-button
                            @click="submitReport(scope.row)"
                            plain
                            type="primary"  >
                        重新提交
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <!--分页-->
        <el-col :span="24" class="toolbar">
            <el-pagination
                    style="text-align: center;"
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :page-size="pager.page_size"
                    :page-sizes="pager.sizes"
                    background
                    :current-page="pager.page_current"
                    layout="prev,pager,next,sizes,total"
                    :total="pager.total">
            </el-pagination>
        </el-col>

        <!--提交自查报告-->
        <el-dialog
                :visible.sync="dialogFormVisible"
                width="400px"
                title="提交自查报告"
                :modal-append-to-body="false"
                :close-on-click-modal='false'>
            <el-form :rules="itemRules"  label-width="80px" ref="taskForm" :model="form">
                    <el-row>
                        <el-col :span="24">
                            <el-form-item prop="year"  label="选择年份" >
                                <el-select
                                        placeholder="年份" v-model="form.year" size="18px">
                                    <el-option :key="item" :label="item" :value="item"
                                               v-for="item in options.years"></el-option>
                                </el-select>
                            </el-form-item>
                            <el-form-item prop="total_bugs"  label="总隐患数" >
                                <el-input
                                        placeholder="请输入总隐患数"
                                        v-model="form.total_bugs" />
                            </el-form-item>
                            <el-form-item prop="total_fix_bugs"  label="已整改数" >
                                <el-input
                                        placeholder="请输入已整改数"
                                        v-model="form.total_fix_bugs" />
                            </el-form-item>
                            <el-form-item prop="file_id"  label="上传报告" >
                                <el-upload
                                        class="upload-demo release-upload"
                                        drag
                                        action=""
                                        :limit="1"
                                        ref="reportFileUpload"
                                        :on-exceed="handleExceed"
                                        :on-success="handleAvatarSuccess"
                                        :on-remove="handleRemove"
                                        :http-request="httpRequest"
                                        :before-upload="beforeAvatarUpload"
                                        :show-file-list="true"
                                        :file-list="fileLists"
                                        :auto-upload="true"
                                        v-loading="fileUplaodLoading"
                                        multiple>
                                    <i class="el-icon-upload"></i>
                                    <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                                    <div class="el-upload__tip" slot="tip">支持上传PDF、Word文件，大小不超过10MB</div>
                                </el-upload>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <div class="clearfix" style="height:20px;text-align:center;padding:20px 0">
                        <el-button v-loading="fileUplaodLoading" style="padding: 3px 0" type="primary" @click="add">提交</el-button>
                        <el-button style="padding: 3px 0" type="primary" plain @click="cancelAdd">取消</el-button>
                    </div>
            </el-form>
        </el-dialog>
    </section>
</template>

<script>
    import { selfCheckReport,selfSubmitReport } from '../../api/report_api'
    import dict from '../../common/js/dict';
    import {getFile,upload_file} from "../../api/common";
    import { saveAs } from 'file-saver';
    export default {
        name:'univReprot',
        data() {
            return {
                //表单header样式
                headerRowStyle: {
                    backgroundColor: "#ddd",
                    color: "#333",
                    textAlign: "center"
                },
                listLoading: true,
                fileUplaodLoading: false,
                //表格数据
                tableData: [],
                currentYear:'2018',
                dict:dict,
                //分页设置
                pager: {
                    sizes: [10, 20, 30, 40, 50],
                    total: 0,
                    page_size: 10,
                    page_current: 1
                },

                dialogFormVisible:false,
                dialogDetailFormVisible:false,
                //添加
                dialogLoading:false,
                form: {
                    college_id:this.$store.state.userInfo.unit_id,
                    college_name:this.$store.state.userInfo.unit_name,
                    year:'',
                    total_bugs:'',
                    total_fix_bugs:'',
                    file_id:'',
                    id:''
                },
                userInfo: this.$store.state.userInfo,
                itemRules: {
                    year: [
                        {required: true, message: '请选择年份', trigger: 'blur'}
                    ],
                    total_bugs: [
                        {required: true, message: '请输入总隐患数', trigger: 'blur'}
                    ],
                    total_fix_bugs:[
                        {required:true,message:'请输入已整改数',trigger:'blur'}
                    ],
                    file_id:[
                        {required:true,message:'请上传报告',trigger:'change'}
                    ]
                },

                fileLists:[],
                options: {
                    years: []
                }
            }
        },
        computed: {
            role() {
                let role_name = this.$store.state.userInfo.role_name || ''

                let role = 1

                if (role_name.indexOf("教育主管部门") > -1) {
                    role = 2
                }
                return role
            }
        },
        methods: {
            //分页page_size发生改变
            handleSizeChange(val) {
                this.pager.page_current = 1;
                this.pager.page_size = val;
                this.getReportList();
            },
            //分页page_current发生改变
            handleCurrentChange(val) {
                this.pager.page_current = val;
                this.getReportList();
            },
            search(){
                this.pager.page_current = 1;
                this.getReportList();
            },
            getReportList(){
                this.listLoading = true;  //显示loading
                let condition = {
                    // check_unit:'北大',
                    check_unit:this.userInfo.unit_name,
                    // year:this.currentYear.toString()
                    // year:'2020'
                };
                let params = {
                    page_size: this.pager.page_size,
                    page_current: this.pager.page_current,
                    condition
                };
                selfCheckReport(params).then((res) => {
                    if (res.data.status == 200) {
                        this.listLoading = false;  //隐藏loading
                        let result = JSON.parse(res.data.datas);
                        this.tableData = result.items;
                        this.pager.total = result.total;
                    } else {
                        if (res.data.status == 401) {
                            this.$router.push('/login');
                        }
                        this.$message.error(res.data.status + " " + res.data.msg);
                    }
                });
            },

            dowReportWord(row){
                this.listLoading = true
                getFile({id:row.file_id}).then(res => {
                    this.listLoading = false
                    if(res.status == 200){
                        if(res.data.status == 200){
                            saveAs(res.data.datas,row.college_name)
                        }
                    } else {
                        if (res.data.status == 401) {
                            this.$router.push('/login');
                        }
                        this.$message.error(res.data.status + " " + res.data.msg);
                    }
                })
            },

            submitReport(row){
                this.dialogFormVisible = true
                if(row) {
                    this.form.id = row.id
                    this.form.year = row.year
                    this.form.file_id = row.file_id
                    this.form.total_bugs = row.total_bugs
                    this.form.total_fix_bugs = row.total_fix_bugs
                    this.form.college_id = this.$store.state.userInfo.unit_id
                    this.form.college_name = this.$store.state.userInfo.unit_name
                }
            },

            initYears() {
                this.currentYear = (new Date()).getFullYear();
                this.form.year = this.currentYear;
                for (let i = this.currentYear; i >= 2018; i--) {
                    this.options.years.push(i);
                }
            },


            //初始化页面
            initData() {
                clearInterval(this.timer)
                if(this.userInfo.unit_name){
                    this.getReportList();
                }else{
                    this.userInfo = this.$store.state.userInfo
                    this.timer = setInterval(this.initData, 100)
                }
            },

            add(){
                this.$refs['taskForm'].validate((valid) => {
                    if (valid) {
                        this.dialogLoading = true;  //显示loading
                        let params = this.form;
                        selfSubmitReport(params).then((res)=>{
                            if(res.data.status == 200){
                                this.$message({
                                    type: 'success',
                                    message: res.data.msg
                                });
                                this.getReportList()
                                this.cancelAdd()
                            } else {
                                if (res.data.status == 401) {
                                    this.$router.push('/login');
                                }
                                this.$message.error(res.data.status + " " + res.data.msg);
                            }
                        });

                    }
                });

            },
            cancelAdd(){
                this.form = {
                        college_id:this.userInfo.unit_id,
                        college_name:this.userInfo.unit_name,
                        year:'',
                        total_bugs:'',
                        total_fix_bugs:'',
                        file_id:'',
                        id:''
                }
                this.fileLists = []
                this.dialogFormVisible = false
                this.dialogLoading = false;
            },

            fixFormatter(row) {
                return  (row.total_fix_bugs /row.total_bugs * 100).toFixed(1) + '%'
            },

            // 上传前对文件的大小的判断
            beforeAvatarUpload (file) {
                const extension1 = file.type.toLowerCase().indexOf('pdf') > -1;
                const extension2 = file.name.toLowerCase().indexOf('doc') > -1;
                if (!extension2 && !extension1) {
                     this.$message({
                        message: '文件格式不正确，请上传PDF、Word文件!',
                        type: 'warning'
                    })
                    return false
                }
                const isLt2M = file.size / 1024 / 1024 < 10
                // if (!extension) {
                //    this.$message.error('上传模板只能是本地 pdf 格式!');
                // }
                if (!isLt2M) {
                     this.$message.error('文件最大支持10MB!');
                    return false
                }
                //return extension && isLt2M;
                return true
            },
            handleExceed(files, fileList) {
                this.$message.warning(`限制只能上传1个文件`);
            },
            handleAvatarSuccess(res, file) {
                this.fileLists = [{'name': file.name, 'url': URL.createObjectURL(file.raw)}];
            },
            handleRemove(res, file) {
                this.fileLists = []
                this.form.file_id = ''
            },
            httpRequest(item,fileLists) {
                let formData = new FormData();
                formData.append('file', item.file);
                this.fileUplaodLoading = true
                upload_file(formData).then((res) => {
                    let result = JSON.parse(res.data.datas);
                    if (res.data.status == 200) {
                        this.form.file_id = result.id
                    } else {
                        if (res.data.status === 401) {
                            this.$router.push('/login');
                        }
                        this.$message.error(res.data.msg);
                        this.fileLists = [];
                    }
                    this.fileUplaodLoading = false
                });
            }

        },
        mounted() {
            this.$nextTick(function () {
                this.initYears();
                this.initData();
            })
        }
    }
</script>

<style scoped>

</style>
